@page "/"
@using System.Text.Json
@using MeiwenDiaryWeb.Components.Controls
@using MeiwenDiaryWeb.Models
@inject SwalService _swalService

<PageTitle>美文日记</PageTitle>

<div class="text-center">
    <Button Text="写日记" style="display: inline-block"
            OnClick="CreateAsync"></Button>
</div>

<div style="height: 12px"></div>

<Timeline Items="@_timelineItems" IsAlternate="true"></Timeline>

<div style="height: 12px"></div>

<div class="text-center">
    <Button OnClick="LoadMoreAsync" style="display: inline-block">加载更多
    </Button>
</div>

<div style="height: 12px"></div>

<Modal @ref="_createModal">
    <ModalDialog SaveButtonText="保存" CloseButtonText="关闭"
                 ShowSaveButton="true" OnSaveAsync="SaveAsync">
        <BodyTemplate>
            <BootstrapInputNumber
                @bind-Value="@_diaryInputModel.Year"
                style="width: auto; display: inline-block"></BootstrapInputNumber>
            /
            <BootstrapInputNumber
                @bind-Value="@_diaryInputModel.Month"
                style="width: auto; display: inline-block"></BootstrapInputNumber>
            /
            <BootstrapInputNumber
                @bind-Value="@_diaryInputModel.DayOfMonth"
                style="width: auto; display: inline-block"></BootstrapInputNumber>
            <div style="height: 12px"></div>
            <Textarea @bind-Value="@_diaryInputModel.Content"
                      rows="10"></Textarea>
            <div style="height: 12px"></div>
            <Button Color="Color.Success" IsDisabled="@_isDisabled"
                    OnClick="MeiwenAsync">美文
            </Button>
            <div style="height: 12px"></div>
            @if (_isDisabled) {
                <Progress IsStriped="true" IsAnimated="true"
                          Value="100" Color="Color.Success"></Progress>
            }
        </BodyTemplate>
    </ModalDialog>
</Modal>

@code {

    private List<TimelineItem> _timelineItems = new();

    protected override async Task OnInitializedAsync() {
        await LoadMoreAsync();
    }

    private async Task LoadMoreAsync() {
        using var httpClient = new HttpClient();
        HttpResponseMessage response;
        try {
            response = await httpClient.GetAsync("http://localhost:35210/diaries?take=20&skip=" + _timelineItems.Count);
            response.EnsureSuccessStatusCode();
        } catch (Exception e) {
            await _swalService.Show(new() { Content = e.Message, Category = SwalCategory.Error });
            return;
        }

        _timelineItems.AddRange(JsonSerializer.Deserialize<IEnumerable<DiaryViewModel>>(await response.Content.ReadAsStringAsync(), new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!.Select(p => new TimelineItem { Component = BootstrapDynamicComponent.CreateComponent<TimelineDiaryControl>(new Dictionary<string, object?> { ["DiaryViewModel"] = p }) }));
    }

    private async Task CreateAsync() => await _createModal.Show();

    private Modal _createModal;

    private DiaryViewModel _diaryInputModel = new() { Year = DateTime.Now.Year, Month = DateTime.Now.Month, DayOfMonth = DateTime.Now.Day, Content = "" };

    private bool _isDisabled = false;

    private async Task MeiwenAsync() {
        _isDisabled = true;
        StateHasChanged();

        using var httpClient = new HttpClient();
        var jsonContent = JsonContent.Create(new { draft = _diaryInputModel.Content }, options: new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
        await jsonContent.ReadAsStringAsync(); // magic code to make it run but why?

        HttpResponseMessage response;
        try {
            response = await httpClient.PostAsync("http://localhost:35220/diaries/generate", jsonContent);
            response.EnsureSuccessStatusCode();
        } catch (Exception e) {
            await _swalService.Show(new SwalOption { Content = e.Message, Category = SwalCategory.Error });
            _isDisabled = false;
            StateHasChanged();
            return;
        }

        _diaryInputModel.Content = await response.Content.ReadAsStringAsync();
        _isDisabled = false;
        StateHasChanged();
    }

    private async Task<bool> SaveAsync() {
        using var httpClient = new HttpClient();
        var jsonContent = JsonContent.Create(new { _diaryInputModel.Year, _diaryInputModel.Month, _diaryInputModel.DayOfMonth, _diaryInputModel.Content }, options: new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
        await jsonContent.ReadAsStringAsync(); // magic code to make it run but why?

        try {
            var response = await httpClient.PostAsync("http://localhost:35210/diaries", jsonContent);
            response.EnsureSuccessStatusCode();
        } catch (Exception e) {
            await _swalService.Show(new SwalOption { Content = e.Message, Category = SwalCategory.Error });
            return false;
        }

        await _swalService.Show(new SwalOption { Content = "日记已保存，请刷新页面以查看变更", Category = SwalCategory.Success });
        return true;
    }

}